package com.gary.springboot.controller;

import com.gary.springboot.dao.DepartmentDao;
import com.gary.springboot.dao.EmployeeDao;
import com.gary.springboot.entities.Department;
import com.gary.springboot.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 *  员工操作控制层
 *  使用restfulCRUD风格
 * @author pengrui
 * @date 2020/11/19 - 11:26
 */
@Controller
public class EmployeeController {

    @Autowired
    public EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;

    @GetMapping("/emps")
    public String getAll(Model model) {
        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("emps", employees);
        return "emp/list";
    }

    /**
     * 跳转到员工添加页面
     * @return
     */
    @GetMapping("/emp")
    public String toAddPage(Model model) {
        Collection<Department> depts = departmentDao.getDepartments();
        model.addAttribute("depts", depts);
        return"emp/add";
    }

    /**
     *  添加员工操作
     * @return
     */
    @PostMapping("/emp")
    public String addEmp(Employee employee) {
        System.out.println(employee);
        employeeDao.save(employee);
        //重定向 发送的url请求，不是使用模板引擎的方式为我们构建页面
        return "redirect:/emps";
    }

    /**
     *  跳转到编辑页面
     *  add  添加 修改页面二合一
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable("id") Integer id, Model model) {
        System.out.println(id);
        //员工数据回显
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp", employee);
        //回显部门信息
        Collection<Department> depts = departmentDao.getDepartments();
        model.addAttribute("depts", depts);
        return "emp/add";
    }

    @PutMapping("/emp")
    public String editEmp(Employee employee) {
        System.out.println(employee);
        return "redirect:/emps";
    }

    @DeleteMapping("/emp/{id}")
    public String deleteEmp(@PathVariable("id") Integer id) {
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
